package com.i2863.receipt.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.i2863.receipt.dao.SiteRepository;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.util.BaseGuavaCache;
import com.i2863.receipt.util.HttpSessionUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/6/8.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SiteServiceImpl extends BaseGuavaCache implements SiteService{

    @Value("${sitelist.url}")
    public String siteListUrl;
    @Value("${siteinfo.url}")
    public String siteInfoUrl;
    @Value("${sitecache.refresh}")
    public Integer siteCacheRefresh;
    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();
    private final static Logger logger = LoggerFactory.getLogger(SiteServiceImpl.class);

    @Resource
    private SiteRepository siteRepository;

    @Override
    public List<Site> findAll() {
        return siteRepository.findAll();
    }

    @Override
    public Site findOne(Integer id) {
        return siteRepository.findOne(id);
    }
    @Override
    public Site findByCode(Integer siteid) {
        return null;
    }

    @Override
    public List<Site> list() {
        List<Site> acctSites = new ArrayList<Site>(128);
        // 获取信息
        String info = null;
        try {
            info = HttpSessionUtils.httpGet(client,siteListUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (info == null || "".equals(info)) {
            return (List<Site>) this.getValue("all");
        }

        JsonParser parser = new JsonParser();
        JsonObject infoObject = (JsonObject) parser.parse(info);

        if (!(("null").equals(infoObject.get("data").toString()) || "".equals((infoObject.get("data").toString())))) {
            JsonArray data = infoObject.get("data").getAsJsonArray();
            for (JsonElement jsonElement : data) {
                Site acctSite = new Site();
                acctSite.setId(jsonElement.getAsJsonObject().get("siteId").getAsInt());
                acctSite.setName(jsonElement.getAsJsonObject().get("siteName").getAsString());
                acctSites.add(acctSite);
                if (System.currentTimeMillis() - Long.parseLong(this.getValue("updateTime").toString()) > 1000 * siteCacheRefresh) {
                    this.put(jsonElement.getAsJsonObject().get("siteId").getAsInt(), acctSite);
                }
            }
            if (System.currentTimeMillis() - Long.parseLong(this.getValue("updateTime").toString()) > 1000 * siteCacheRefresh) {
                this.put("all", acctSites);
                this.put("updateTime", System.currentTimeMillis());
                logger.info("站点缓存已成功刷新！");
            }
        }
        return acctSites;
    }

    @Override
    public Site findBySiteId(Integer siteId) {
        Site acctSite = null;
        // 获取信息
        String info = null;
        try {
            info = HttpSessionUtils.httpGet(client,siteInfoUrl+"?siteId="+siteId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (info == null || "".equals(info)) {
            if (this.getValue(siteId) instanceof Site) {
                return (Site) this.getValue(siteId);
            } else {
                return null;
            }
        }

        JsonParser parser = new JsonParser();
        JsonObject infoObject = (JsonObject) parser.parse(info);

        if (!(("null").equals(infoObject.get("data").toString()) || "".equals((infoObject.get("data").toString())))) {
            JsonObject data = infoObject.get("data").getAsJsonObject();
            acctSite = new Site();
            acctSite.setId(data.get("siteId").getAsInt());
            acctSite.setName(data.get("siteName").getAsString());
        }

        return acctSite;
    }

    @Override
    public void setImg(String imgUrl, Integer siteId) {
        siteRepository.updateImg(imgUrl,siteId);
    }

    @Override
    protected Object getValueWhenExpired(Object key) {
        return "0";
    }

    @Override
    public void add(Site site) {
        siteRepository.save(site);
    }
}
